package com.ruoyi.project.pay.weixin.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Filename: WxToolUtil.java <br>
 * <p>
 * Description: 微信支付公共util<br>
 *
 * @author: rongrong <br>
 * @version: 1.0 <br>
 * @Createtime: 2019-12-02 <br>
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 * 2019-12-02       rongrong            v1.0              第一次创建
 * @Copyright: Copyright (c)2019 by rongrong <br>
 */
public class WxToolUtil {

    /**
     * 获取时间戳
     * @return
     */
    public static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis()).substring(0, 10);
    }

    /**
     * 获取随机字符串
     * @return
     */
    public static String getNonce_str() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().substring(5, 25);
    }

    /**
     * 获取客户端的ip地址
     * @return
     */
    public static String getIpAddress() {
        try{
            HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        }catch (Exception e) {
            return null;
        }
    }

    /**
     * 微信APP支付成功返回
     * @return
     */
    public static String success(){
        Map<String, String> return_data = new HashMap<>();
        // 支付失败
        return_data.put("return_code", "FAIL");
        return_data.put("return_msg", "return_code不正确");
        return XMLUtil.GetMapToXML(return_data);
    }

    /**
     * 微信APP支付失败返回
     * @param msg 异常信息
     * @return
     */
    public static String fail(String msg){
        Map<String, String> return_data = new HashMap<>();
        // 支付失败
        return_data.put("return_code", "FAIL");
        return_data.put("return_msg", msg);
        return XMLUtil.GetMapToXML(return_data);
    }

}
